package com.zfc.freemyleft.freetrymyleftframe.push;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;

import com.alibaba.fastjson.JSONObject;
import com.freemyleft.left.zapp.util.LeftLogger;
import com.zfc.freemyleft.freetrymyleftframe.ExampleActivity;

import java.util.Set;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by FreeMyleft on 2018/2/28.
 */

public class PushReceiver extends BroadcastReceiver {
    //我们需要获得极光推送的信息 需要判断一些东西
    @Override
    public void onReceive(Context context, Intent intent) {
        final Bundle bundle=intent.getExtras();
        final Set<String>keys=bundle.keySet();
        JSONObject json=new JSONObject();
        for (String key:keys){
            final Object val=bundle.get(key);
            json.put(key,val);
        }
        LeftLogger.json("PushReceiver",json.toJSONString());
        final String pushAction=intent.getAction();
        if (pushAction.equals(JPushInterface.ACTION_NOTIFICATION_RECEIVED)){
            //处理接受到的信息
            OnReceiverMessage(bundle );
        }else if (pushAction.equals(JPushInterface.ACTION_NOTIFICATION_OPENED)){
            //打开相应的通知
            onOpenNotification(context,bundle);
        }
    }
    /**
     * 处理接收到的信息
     */
    private void OnReceiverMessage(Bundle bundle){
        final String title = bundle.getString(JPushInterface.EXTRA_NOTIFICATION_TITLE);//额外的通知的标题
        final String msgId = bundle.getString(JPushInterface.EXTRA_MSG_ID);//额外的消息id
        final int notificationId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);//额外的通知id
        final String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);//额外的消息
        final String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
        final String alert = bundle.getString(JPushInterface.EXTRA_ALERT);//警告

    }
    /**
     * 打开相应的通知
     */
    private void onOpenNotification(Context context, Bundle bundle) {
        final String extra = bundle.getString(JPushInterface.EXTRA_EXTRA);
        final Bundle openActivityBundle = new Bundle();
        final Intent intent = new Intent(context, ExampleActivity.class);
        //通过bundle启动相应的页面
        intent.putExtras(openActivityBundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        ContextCompat.startActivity(context, intent, null);
    }
}
